<script setup lang="ts">
import type { JsonHttpResponse } from '@/utils/http'
import { sendRequest } from '@/utils/api'
import { type FormInst, NButton } from 'naive-ui'
import { ref, onMounted } from 'vue'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'

const formInst = ref<FormInst | null>(null)
const formData = ref({} as Record<string, unknown>)
const handleUpdateFormData = (key: string, value: unknown) => {
  formData.value[key] = value
}
const handleSubmit = () => {
  formInst.value?.validate((error) => {
    if (error) return
    alert(JSON.stringify(formData.value, null, 2))
  })
}

const modelJson = ref({} as ModelJson)
const queryJson = async (code: string) => {
  try {
    const [error, res] = await sendRequest<JsonHttpResponse<ModelJson>>({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    modelJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}

onMounted(() => queryJson('T001001_TEST'))
</script>

<template>
  <DynamicPageForm
    ref="formInst"
    :form-model="modelJson"
    :model="formData"
    :form-data="formData"
    label-placement="left"
    require-mark-placement="left"
    label-width="140rem"
    @update:value="handleUpdateFormData"
  />

  <NButton
    style="width: 200px; margin: 100px auto 0; display: flex"
    type="primary"
    @click="handleSubmit"
  >
    提交
  </NButton>
</template>
